let data = {};
let editingId = null;
let requestUrl = null;
let wearArray = ["&ensp;穿&ensp;戴&ensp;", "&ensp;卸&ensp;下&ensp;", "替&ensp;换&ensp;"];

function addHandler() {
    requestUrl = "/chongwu_shizhuang/insert";

    $("#yuehuahuanyi_dialog").dialog("open");
}

function editHandler() {
    let rowData = $("#yuehuahuanyi_list").datagrid("getSelected");

    if(rowData) {
        requestUrl = "/chongwu_shizhuang/updateById";

        $("#id").val(rowData.id);
        $("#score").numberspinner("setValue", rowData.score);
        $("#roleId").combobox("setValue", rowData.roleId);
        $("#chongwuId").combogrid("setValue", rowData.chongwuId);
        $("#categoryId").combobox("setValue", rowData.categoryId);

        $("#yuehuahuanyi_dialog").dialog("open");
    } else {
        alertMsg("请选择要修改的记录！", "warning");
    }
}

function inlayHandler() {
    let rowData = $("#yuehuahuanyi_list").datagrid("getSelected");

    if (rowData) {
        $("#chongwu_list").datalist("reload", {
            fallback: function () {
                $("#chongwu_list").datalist("selectRecord", rowData.chongwuId);
            }
        });
    } else {
        $("#chongwu_list").datalist("reload");
    }

    $("#xiangqian_dialog").dialog("open");
}

function attributeHandler() {
    let rowData = $("#yuehuahuanyi_list").datagrid("getSelected");

    if (rowData) {
        $("#property_list").datagrid("load", {
            shizhuangId: rowData.id
        });

        $("#property_dialog").dialog("open");
    } else {
        unselected();
    }
}

function deleteHandler() {
    let rowData = $("#yuehuahuanyi_list").datagrid("getSelected");

    if (rowData) {
        $.messager.confirm("提示", "是否确认删除？", function(bool) {
            if (bool) {
                ajaxPost("/chongwu_shizhuang/deleteById", {
                    id: rowData.id
                }, function(response) {
                    showMsg(response.message);

                    $("#yuehuahuanyi_list").datagrid("reload");
                }, error);
            }
        });
    } else {
        alertMsg("请选择要删除的记录！");
    }
}

function computeHandler() {
    let rowData = $("#yuehuahuanyi_list").datagrid("getSelected");

    if (rowData) {
        ajaxPost("/chongwu_shizhuang/compute", {
            shizhuangId: rowData.id
        }, function(resp) {
            showMsg(resp.message);

            $("#yuehuahuanyi_list").datagrid("reload");
        }, error);
    } else {
        unselected();
    }
}

$(document).ready(function() {

    fetchSelect("#categoryId", "/chongwu_shizhuang_category/selectAll", {
        width: 150,
        editable: true,
        required: true,
        formatter: function(row) {
            return "<img src='" + row.image + "' height='18' />&nbsp;" + row.name;
        }
    });

    $("#score").numberspinner({
        min: 0,
        width: 150,
        required: true
    });

    $("#chongwuId").combogrid({
        url: "/chongwu/selectAll",
        method: "get",
        idField: "id",
        textField: "name",
        width: 150,
        panelWidth: 365,
        panelHeight: "auto",
        columns: [[
            {field: "name", title: "宠物名字", align: "center", width: 88},
            {field: "categoryId", title: "宠物类型", align: "center", width: 88,
                formatter: function(value, rowData, rowIndex) {
                    if (value) {
                        ajaxGet("/chongwu_category/selectById", {
                            id: value
                        }, function (resp) {
                            let data = resp.data;

                            $("#_chongwu_" + rowIndex).attr("src", data.image)
                                .attr("title", data.name);
                        }, error);

                        return "<img height='32' id='_chongwu_" + rowIndex + "'  />";
                    } else {
                        return "<div>无</div>";
                    }
                }
            },
            {field: "grade", title: "等级", align: "center", width: 88,
                formatter: function(value) {
                    return "<span>" + value + "级</span>";
                }
            },
            {field: "score", title: "评分", align: "center", width: 88}
        ]]
    });

    fetchSelect("#roleId", "/role_account/selectAll", {
        width: 150,
        editable: true,
        required: true,
        formatter: function(row) {
            ajaxGet("/role_category/selectById", {
                id: row.categoryId
            }, function(resp) {
                let data = resp.data;

                $("#role_" + row.id).attr("title", data.name)
                    .attr("src", data.image);
            }, error);

            return "<img height='20' id='role_" + row.id + "' />&ensp;" + row.name;
        }
    });

    $("#yuehuahuanyi_dialog").dialog({
        title: "宠物时装",
        width: 500,
        height: 300,
        buttons: [{
            iconCls: "icon-save",
            text: "保存",
            handler: function() {
                let selector = "#yuehuahuanyi_form";

                checkForm(selector, function () {
                    let data = $(selector).serialize();

                    ajaxPost(requestUrl, data, function(response) {
                        showMsg(response.message);

                        $(selector).form("clear");
                        $("#yuehuahuanyi_dialog").dialog('close');
                        $("#yuehuahuanyi_list").datagrid("reload");
                    }, error);
                });
            }
        }, {
            iconCls: "icon-cancel",
            text: "取消",
            handler: function() {
                $("#yuehuahuanyi_form").form("clear");
                $("#yuehuahuanyi_dialog").dialog("close");
            }
        }]
    });

    /******************************************************************************************************/

    $("#chongwu_list").datalist({
        url: "/chongwu/selectAll",
        idField: "id",
        valueField: "id",
        textField: "name",
        width: 240,
        height: 346,
        textFormatter: function(value, rowData, rowIndex) {
            ajaxGet("/chongwu_category/selectById", {
                id: rowData.categoryId
            }, function(res) {
                let data = res.data;

                $("#name_" +  rowData.id).html(rowData.name);
                $("#grade_" +  rowData.id).html(rowData.grade);
                $("#score_" +  rowData.id).html(rowData.score);
                $("#chongwu_" +  rowData.id).attr({
                    "src": data.image,
                    "title": data.name
                });
            }, error);

            let content = "";

            content += "<table>";
            content += 	"<tr>";
            content += 		"<td rowspan=2>";
            content += 			"<div style='border:1px black solid;width:54px;height:54px;'>";
            content +=					"<img width='52' id='chongwu_" +  rowData.id + "'  />";
            content +=				"<div>";
            content += 		"</td>";
            content += 	"</tr>";

            content += 	"<tr>";
            content += 		"<td>";
            content += 			"<div>";
            content +=					"<div id='name_" +  rowData.id + "'></div>";
            content +=					"<span id='grade_" +  rowData.id + "'></span>" + "级<br/>";
            content +=					"评分：<span id='score_" +  rowData.id + "'></span>";
            content += 			"</div>";
            content += 		"</td>";
            content += 	"</tr>";
            content += "</table>";

            return content;
        },
        onSelect: function(rowIndex, rowData) {
            if (rowData) {
                ajaxGet("/chongwu_category/selectById", {
                    id: rowData.categoryId
                }, function (resp) {
                    let data = resp.data;

                    $("#chongwu_image").prop("src", data.image);
                }, error);

                $("#chongwu_grade").html(rowData.grade);
                $("#chongwu_name").html(rowData.name);
                $("#chongwu_score").html(rowData.score);

                $("#shizhuang_list").datalist("reload", {
                    chongwuId: rowData.categoryId
                }).datagrid("unselectAll");
            }
        }
    });

    $("#shizhuang_list").datalist({
        url: "/chongwu_shizhuang/selectByChongwuId",
        idField: "id",
        width: 228,
        height: 290,
        textFormatter: function(value, rowData, rowIndex) {
            ajaxGet("/chongwu_shizhuang_category/selectById", {
                id: rowData.categoryId
            }, function(resp) {
                let chongwuId = rowData.chongwuId;

                if (chongwuId) {
                    ajaxGet("/chongwu/selectById", {
                        id: chongwuId
                    }, function (resp) {
                        let data = resp.data;

                        if (data) {
                            $("#chongwu_name_" + rowIndex).html(data.name).show();
                        }
                    }, error);
                } else {
                    $("#chongwu_name_" + rowIndex).hide();
                }

                let data = resp.data;

                $("#shizhuang_score_" + rowIndex).html(rowData.score);
                $("#shizhuang_image_" +  rowIndex).attr("src", data.image);

                ajaxGet("/chongwu_shizhuang_attribute/selectAttribute", {
                    shizhuangId: rowData.id
                }, function (resp) {
                    let attribute = resp.data;

                    if (attribute) {
                        let propertyValue = attribute.propertyValue;

                        $("#value_" + rowIndex).progressbar({
                            width: 80,
                            text: "{value}"
                        }).progressbar("setValue", propertyValue).show();

                        $("#property_name_" + rowIndex).html(attribute.propertyName).show();

                        ajaxGet("/chongwu_shizhuang_view_attribute/select", {
                            propertyId: attribute.propertyId,
                            grade: data.grade
                        }, function (resp) {
                            let color;
                            let data = resp.data;
                            let percent = propertyValue / data.max;

                            if (percent >= 0.9) {
                                color = "orange";
                            } else if (percent >= 0.8) {
                                color = "purple";
                            } else if (percent >= 0.6) {
                                color = "blue";
                            } else {
                                color = "green";
                            }

                            $("#value_" + rowIndex).progressbar("setColor", color);
                            $("#value_" + rowIndex).progressbar("setText", "{value}/" + data.max);
                            $("#value_" + rowIndex).progressbar("setPercent", percent * 100);
                        }, error);
                    } else {
                        $("#value_" + rowIndex).hide();
                        $("#property_name_" + rowIndex).empty().hide();
                    }
                }, error);
            }, error);

            let html = "";

            html += "<table>";
            html += 	"<tr>";
            html += 		"<td rowspan=2>";
            html += 			"<div style='border:1px black solid;width:54px;height:54px;'>";
            html +=					"<img width='52' id='shizhuang_image_" +  rowIndex + "' />";
            html +=				"<div>";
            html += 		"</td>";

            html += 		"<td>";
            html +=				"<div id='property_name_" +  rowIndex + "'>气血</div>";
            html += 		"</td>";

            html += 		"<td>";
            html +=				"<div id='value_" +  rowIndex + "'></div>";
            html += 		"</td>";
            html += 	"</tr>";

            html += 	"<tr>";
            html += 		"<td colspan='3'>";
            html += 			"<div>";
            html +=					"评分+<span id='shizhuang_score_" +  rowIndex + "'></span>";
            html +=					"&emsp;<button id='chongwu_name_" +  rowIndex + "'></button>";
            html += 			"</div>";
            html += 		"</td>";
            html += 	"</tr>";
            html += "</table>";

            return html;
        },
        onSelect: function(rowIndex, rowData) {
            if (rowData) {
                ajaxGet("/chongwu_shizhuang_category/selectById", {
                    id: rowData.categoryId
                }, function (resp) {
                    let data = resp.data;

                    $("#shizhuang_name").html(data.name);
                    $("#chongwu_image").attr("src", data.image);
                }, error);

                let wearStatus = rowData.wearStatus;

                $("#wear").linkbutton({
                    text: wearArray[wearStatus]
                });

                if (wearStatus === 1) {
                    let chongwu = $("#chongwu_list").datalist("getSelected");

                    if (chongwu.id !== rowData.chongwuId) {
                        $("#wear").linkbutton({
                            text: wearArray[2]
                        })
                    }
                }

                $("#shizhuang_score").html(rowData.score);
            }
        }
    });

    $("#add").linkbutton({
        text: "附加属性"
    }).click(function() {
        let rowData = $("#shizhuang_list").datalist("getSelected");

        if (rowData) {
            $("#property_list").datagrid("load", {
                shizhuangId: rowData.id
            });

            $("#property_dialog").dialog("open");
        } else {
            unselected();
        }
    });

    $("#wear").linkbutton({
        text: wearArray[0]
    }).click(function() {
        let chongwu = $("#chongwu_list").datalist("getSelected");

        if (chongwu) {
            let shizhuang = $("#shizhuang_list").datalist("getSelected");

            if (shizhuang) {
                ajaxPost("/chongwu_shizhuang/wear", {
                    chongwuId: chongwu.id,
                    shizhuangId: shizhuang.id,
                }, function (resp) {
                    showMsg(resp.message);

                    $("#shizhuang_list").datalist("reload").datagrid("unselectAll");
                }, error);
            } else {
                alertMsg("请选择宠物！");
            }
        } else {
            alertMsg("请选择宠物！");
        }
    });

    $("#xiangqian_dialog").dialog({
        title: "月华幻衣"
    });

    /******************************************************************************************************/

    $("#property_list").datagrid({
        url: "/chongwu_shizhuang_attribute/selectByShizhuangId",
        method: "get",
        width: 500,
        height: 300,
        onAfterEdit: function (rowIndex, rowData, changes) { // 结束行内编辑事件
            data = {
                id: rowData.id,
                shizhuangId: rowData.shizhuangId,
                propertyId: changes.propertyId ? changes.propertyId : rowData.propertyId,
                propertyValue: changes.propertyValue ? changes.propertyValue : rowData.propertyValue
            };
        },
        toolbar: [{
            iconCls: "icon-add",
            text: "添加",
            handler: function() {
                let rowData = $("#yuehuahuanyi_list").datagrid("getSelected");

                if(rowData) {
                    let datagrid = $("#property_list");

                    datagrid.datagrid("appendRow",{
                        id: null,
                        propertyId: null,
                        propertyValue: 0,
                        shizhuangId: rowData.id
                    });

                    let total = datagrid.datagrid("getRows").length;

                    editingId = total - 1;
                    requestUrl = "/chongwu_shizhuang_attribute/insert";

                    datagrid.datagrid("beginEdit", editingId);
                } else {
                    unselected("请选择一件装备~");
                }
            }
        }, "-", {
            iconCls: "icon-edit",
            text: "修改",
            handler: function() {
                let datagrid = $("#property_list");

                if (editingId != null) {
                    datagrid.datagrid("selectRow", editingId);
                } else {
                    let row = datagrid.datagrid("getSelected");

                    if (row) {
                        // 获取行索引，这个索引从0开始
                        let rowIndex = datagrid.datagrid("getRowIndex", row);

                        editingId = rowIndex;
                        requestUrl = "/chongwu_shizhuang_attribute/updateById";

                        datagrid.datagrid("beginEdit", rowIndex);
                    } else {
                        unselected();
                    }
                }
            }
        }, "-", {
            iconCls: "icon-save",
            text: "保存",
            handler: function() {
                if (editingId != null) {
                    // 只有结束编辑才能获取到最新的值
                    $("#property_list").datagrid("endEdit", editingId);

                    ajaxPost(requestUrl, data, function(resp) {
                        editingId = null;
                        showMsg(resp.message);

                        $("#property_list").datagrid("reload");
                    }, error);
                }
            }
        }, "-", {
            iconCls: "icon-cancel",
            text: "取消",
            handler: function() {
                if (editingId != null) {
                    $("#property_list").datagrid("cancelEdit", editingId);

                    editingId = null;
                }
            }
        }, "-", {
            iconCls: "icon-delete",
            text: "删除",
            handler: function() {
                let rowData = $("#property_list").datagrid("getSelected");

                if(rowData) {
                    $.messager.confirm("提示", "是否确认删除？", function(bool) {
                        if (bool) {
                            ajaxPost("/chongwu_shizhuang_attribute/deleteById", {
                                id: rowData.id
                            }, function(resp) {
                                showMsg(resp.message);

                                $("#property_list").datagrid("reload");
                            }, error);
                        }
                    });
                } else {
                    alertMsg("请选择一条记录！", "warning");
                }
            }
        }],
        columns: [[
            {field: "id", hidden: true},
            {field: "shizhuangId", hidden: true},
            {field: "propertyId", title: "属性", align: "center", width: 150
                , editor: {
                    type: "combobox",
                    options: {
                        url: "/property/selectByType?type=1",
                        valueField: "id",
                        textField: "name",
                        panelHeight: "auto"
                    }
                }
                , formatter: function(value, rowData, rowIndex) {
                    if (value) {
                        ajaxGet("/property/selectById", {
                            id: value
                        }, function (resp) {
                            let data = resp.data;

                            $("#property_" + rowIndex).html(data.name);
                        }, error);

                        return "<div class='blue' id='property_" + rowIndex + "'></div>";
                    }
                }
            },
            {field: "propertyValue", title: "属性值", align: "center", width: 150, editor: "numberspinner"}
        ]]
    });

    $("#property_dialog").dialog({
        title: "月华幻衣属性",
        height: 340
    });

    /******************************************************************************************************/

    /**
     * 表格体的高度
     * @type {number}
     */
    let heigt_body = heigt_tr_with_role_details * 10;
    /**
     * 表格高度
     * @type {number}
     */
    let height_table = heigt_tool + heigt_header + heigt_body + heigt_footer + heigt_scoll_bar + 2;

    $("#yuehuahuanyi_list").datagrid({
        url: "/chongwu_shizhuang/selectByPage",
        method: "get",
        height: height_table,
        rownumbers: true,
        fitColumns: true,
        pagination: true,
        toolbar: [{
            iconCls: "icon-add",
            text: "添加",
            handler: function() {
                addHandler();
            }
        }, "-", {
            iconCls: "icon-edit",
            text: "修改",
            handler: function() {
                editHandler();
            }
        }, "-", {
            iconCls: "icon-baoshi",
            text: "镶嵌",
            handler: function() {
                inlayHandler();
            }
        }, "-", {
            iconCls: "icon-shield",
            text: "属性",
            handler: function() {
                attributeHandler();
            }
        }, "-", {
            iconCls: "icon-delete",
            text: "删除",
            handler: function() {
                deleteHandler();
            }
        }, "-", {
            iconCls: "icon-ok",
            text: "计算评分",
            handler: function() {
                computeHandler();
            }
        }],
        columns: [[
            {field: "id", title: "编号", align: "center", width: 160},
            {field: "categoryId", title: "时装类型", align: "center", width: 160
                , formatter: function(value, rowData, rowIndex) {
                    ajaxGet("/chongwu_shizhuang_category/selectById", {
                        id: value
                    }, function(resp) {
                        let data = resp.data;

                        $("#category_" + rowIndex).attr({
                            "alt": data.name,
                            "src": data.image,
                            "title": data.name
                        });
                    }, error);

                    return "<img height='" + size + "' id='category_" + rowIndex + "' />";
                }
            },
            {field: "score", title: "时装评分", align: "center", width: 160},
            {field: "chongwuId", title: "穿戴宠物", align: "center", width: 160
                , formatter: function(value, rowData, rowIndex) {
                    if (value) {
                        ajaxGet("/chongwu/selectById", {
                            id: value
                        }, function (resp) {
                            let data = resp.data;

                            $("#chongwu_" + rowIndex).attr("title", data.name);

                            ajaxGet("/chongwu_category/selectById", {
                                id: data.categoryId
                            }, function (resp) {
                                let data = resp.data;

                                $("#chongwu_" + rowIndex).attr("src", data.image);
                            }, error);
                        }, error);

                        return "<img height='" + size + "' id='chongwu_" + rowIndex + "' />";
                    } else {
                        return "<span>/</span>"
                    }
                }
            },
            roleDetailsColumn
        ]]
    });

});